package com.spj.shiro;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * @author :spj
 * @Date:2022/4/14
 * @description:
 */
public class JwtUtil {
    public static Date setOutTime(int minute){
        Date date = new Date(System.currentTimeMillis() + minute*60*1000);
        return date;
    }
    public static String sign(String username,String password){
        Algorithm algorithm = Algorithm.HMAC256(password);
        String token = JWT.create().withClaim("username", username)
                .withSubject(username)
                .withExpiresAt(setOutTime(15))
                .sign(algorithm);
        return token;
    }
    public static boolean verify(String token,String username,String password){
        Algorithm algorithm = Algorithm.HMAC256(password);
        JWTVerifier jwtVerifier = JWT.require(algorithm)
                .withClaim("username",username)
                .withSubject(username).build();
        //检验不成功会报异常
        DecodedJWT decode=jwtVerifier.verify(token);
        return true;
    }
    public static String getSubject(String token){
        DecodedJWT decode = JWT.decode(token);
        return decode.getSubject();
    }
}

